<template>
  <div class="chart pad">
    <div class="head">
      <span>健康档案总表维护</span>
      <el-button @click="handleAdd" type="primary" icon="el-icon-plus" circle></el-button>
    </div>
    <el-tabs class="m-t-b" type="border-card">
      <el-tab-pane label="当前版本">
        <el-table class="m-t-b" :data="charts" stripe border v-loading="loading">
          <el-table-column label="" type="expand" width="100">
            <template slot-scope="scope">
              <div>
                <span style="font-weight: bold; padding-right: 4px;">简介: </span>
                <span>{{scope.row.describe || '暂无简介'}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="表名" prop="name"></el-table-column>
          <el-table-column label="周期">
            <template slot-scope="scope">
              {{scope.row.cycle}}天
            </template>
          </el-table-column>
          <el-table-column label="排序">
            <template slot-scope="scope">
              {{scope.row.sort || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="所属分类">
            <template slot-scope="scope">
              {{scope.row.chartCategoryTitle || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <!-- <el-table-column label="简介">
            <template slot-scope="scope">
              {{scope.row.describe || '暂无'}}
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="图标">
            <template slot-scope="scope">
              <img
                style="width: 60px; height: 60px; cursor: pointer;"
                :src="scope.row.icon"
                v-if="scope.row.icon"
                @click="previewIcon(scope.row.icon)"
              />
              <span v-if="!scope.row.icon">暂无</span>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" fixed="right" width="150">
            <template slot-scope="scope">
              <el-button @click="goDetail(scope.row, 'current')" type="text" size="min">查看</el-button>
              <el-button @click="updateChart(scope.row)" type="text" size="min">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleCurPage"
          :total="curTotal">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="历史版本">
        <el-table class="m-t-b" :data="historyCharts" stripe border v-loading="loading1">
          <el-table-column label="" type="expand" width="100">
            <template slot-scope="scope">
              <div>
                <span style="font-weight: bold; padding-right: 4px;">简介: </span>
                <span>{{scope.row.describe || '暂无简介'}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="表名" prop="name"></el-table-column>
          <el-table-column label="周期">
            <template slot-scope="scope">
              {{scope.row.cycle}}天
            </template>
          </el-table-column>
          <el-table-column label="排序">
            <template slot-scope="scope">
              {{scope.row.sort || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="所属分类">
            <template slot-scope="scope">
              {{scope.row.chartCategoryTitle || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <!-- <el-table-column label="简介">
            <template slot-scope="scope">
              {{scope.row.describe || '暂无'}}
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="图标">
            <template slot-scope="scope">
              <img
                style="width: 60px; height: 60px; cursor: pointer;"
                :src="scope.row.icon"
                v-if="scope.row.icon"
                @click="previewIcon(scope.row.icon)"
              />
              <span v-if="!scope.row.icon">暂无</span>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" fixed="right" width="100">
            <template slot-scope="scope">
              <el-button @click="goDetail(scope.row, 'history')" type="text" size="min">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleHistoryPage"
          :total="historyTotal">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="dialogTitle" :visible.sync="showAddDialog">
      <el-form ref="chart" :model="chart" :rules="rules" label-position="top">
        <el-form-item label="表名" prop="name">
          <el-input v-model="chart.name" />
        </el-form-item>
        <el-form-item label="所属分类" prop="category">
          <el-select v-model="chart.category">
            <el-option
              v-for="(item, i) in categoryList"
              :key="i"
              :label="item.categoryTitle"
              :value="item.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="chart.description" type="textarea" rows="8" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input
            type="number"
            v-model="chart.sort"
            placeholder="数字越小列表显示时越靠前" min="1"
          />
        </el-form-item>
        <!-- <el-form-item label="图标" prop="icon">
          <div>
            <img :src="chart.icon" v-if="chart.icon" style="width: 60px; height: 60px;" />
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :http-request="uploadIcon"
              :show-file-list	="false"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
        </el-form-item> -->
        <el-form-item label="周期设置">
          <el-input-number v-model="chart.cycle" :min="1" :max="10"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="addChart('chart')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看图标" :visible.sync="showImg">
      <div style="text-align: center;">
        <img :src="iconSrc" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { notifySuccess, formatDate, fileToBase64 } from '../util'
import {
  getCurrentSChartList,
  getHistorySChartList,
  uploadImage,
  updateSChart,
  addSChart,
  getAllCategory
} from '../api'

export default {
  name: 'health_chart',
  data () {
    return {
      uploadUrl: '',
      dialogTitle: '添加s表',
      showAddDialog: false,
      showImg: false,
      loading: true,
      loading1: true,
      pageSize: 10,
      iconSrc: '',
      letters: ['A', 'B', 'C', 'D'],
      curTotal: 0,
      historyTotal: 0,
      curTableId: '',
      categoryList: [],
      chart: {
        name: '',
        cycle: 0,
        sort: '',
        icon: '',
        category: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '所属分类不能为空', trigger: 'change' }
        ]
      },
      charts: [],
      historyCharts: []
    }
  },
  methods: {
    handleAdd () {
      if (!this.$checkAuth('canAddSChart')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.dialogTitle = '添加s表';
      this.chart.name = '';
      this.chart.cycle = '';
      this.chart.sort = '';
      // this.chart.icon = '';
      this.chart.category = '';
      this.chart.description = '';
      this.showAddDialog = true
    },
    handleCurPage (page) {
      this.fetchCurSChartList(page)
    },
    handleHistoryPage (page) {
      this.fetchHistorySChartList(page)
    },
    updateChart (row) {
      if (!this.$checkAuth('canEditCurrentChart')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.dialogTitle = '修改s表';
      this.chart.name = row.name;
      this.chart.cycle = row.cycle;
      this.chart.sort = row.sort;
      // this.chart.icon = row.icon;
      this.chart.category = row.chartCategoryId;
      this.chart.description = row.describe;
      this.chart.tableId = row.tableId;
      this.showAddDialog = true
    },
    previewIcon (src) { // 查看图标
      this.iconSrc = src;
      this.showImg = true
    },
    uploadIcon ({ file }) { // 上传s表icon图标
      fileToBase64(file, (base64) => {
        uploadImage(base64)
        .then(res => {
          if (res.data.code === 1) {
            let { path } = res.data.data;
            let pathArr = path.split(':');
            this.chart.icon = `${pathArr[0]}s:${pathArr[1]}`
          } else {
            this.$message.error(res.data.msg || '上传失败!')
          }
        })
        .catch(e => {
          this.$message.error('上传失败!')
        })
      })
    },
    goDetail (data, type) {
      switch (type) {
        case 'current':
          if (!this.$checkAuth('canSeeCurrentChart')) {
            return this.$message.error('暂无对应操作权限!')
          };
          this.$router.push('/file/chart/current/' + data.name + '/' + data.tableId)
          break
        case 'history':
          if (!this.$checkAuth('canSeeHistoryChart')) {
            return this.$message.error('暂无对应操作权限!')
          };
          this.$router.push('/file/chart/history/' + data.name + '/' + data.tableId)
          break
        default:
          break
      }
    },
    addChart (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.dialogTitle === '添加s表') {
            let arr = this.charts.filter(item => item.sort === Number(this.chart.sort))
            if (arr.length) {
              return this.$message.error('此排序已存在!')
            };
            addSChart({
              name: this.chart.name,
              cycle: Number(this.chart.cycle),
              sort: Number(this.chart.sort),
              chartCategoryId: this.chart.category,
              describe: this.chart.description
              // icon: this.chart.icon
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showAddDialog = false
                this.fetchCurSChartList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          } else {
            updateSChart({
              tableId: this.chart.tableId,
              name: this.chart.name,
              cycle: Number(this.chart.cycle),
              sort: Number(this.chart.sort),
              chartCategoryId: this.chart.category,
              describe: this.chart.description
            })
            .then(res => {
              if (res.data.code === 1) {
                this.showAddDialog = false;
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.fetchCurSChartList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    addBlank () {
      this.chart.blanks.push({ value: '' })
    },
    deleteBlank (index) {
      for (let i = 0; i < this.chart.blanks.length; i++) {
        if (index === i) {
          this.chart.blanks.splice(index, 1)
        }
      }
    },
    deleteSelect (index) {
      for (let i = 0; i < this.chart.selects.length; i++) {
        if (index === i) {
          this.chart.selects.splice(index, 1)
        }
      }
    },
    addSelect () {
      this.chart.selects.push({
        name: '',
        answers: [{ value: '' }, { value: '' }, { value: '' }, { value: '' }]
      })
    },
    fetchCurSChartList (index) { // 获取当前版本的s表
      this.loading = true;
      getCurrentSChartList({
        index,
        count: this.pageSize
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || []
          for (let i = 0; i < list.length; i ++) {
            list[i].createDate = formatDate(list[i].createDate)
          }
          this.curTotal = res.data.data.totalRecord
          this.charts = list.sort((a, b) => a.sort - b.sort)
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading = false
      })
      .catch(e => {
        this.$message.error('网络异常!')
        this.loading = false
      })
    },
    fetchHistorySChartList (index) { // 获取历史版本的s表
      this.loading1 = true;
      getHistorySChartList({
        index,
        count: this.pageSize
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.historyTotal = res.data.data.totalRecord;
          for (let i = 0; i < list.length; i ++) {
            list[i].createDate = formatDate(list[i].createDate)
          }
          this.historyCharts = list
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading1 = false
      })
      .catch(e => {
        this.$message.error('网络异常!')
        this.loading1 = false
      })
    },
    fetchCategory () { // 获取分类列表
      getAllCategory()
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          this.categoryList = list
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    }
  },
  created () {
    this.uploadUrl = this.$uploadUrl;
    this.fetchCurSChartList(1)
    this.fetchHistorySChartList(1);
    this.fetchCategory()
  }
}
</script>
<style lang="scss">
  .chart {
    table {
      .cell {
        text-align: center;
      }
    }
  }
</style>
